package com.caocaog.market.handler;

import com.caocaog.market.entity.dto.NightFare;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.jeecg.common.exception.TypeConversionException;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class NightFaresHandler extends BaseTypeHandler<List<NightFare>> {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int columnIndex, List<NightFare> nightFareList, JdbcType jdbcType) throws SQLException {
        try {
            preparedStatement.setString(columnIndex, MAPPER.writeValueAsString(nightFareList));
        } catch (JsonProcessingException e) {
            throw new TypeConversionException(e.getMessage());
        }
    }

    @Override
    public List<NightFare> getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        return this.getNullableResult(resultSet.getString(columnName));
    }

    @Override
    public List<NightFare> getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        return this.getNullableResult(resultSet.getString(columnIndex));
    }

    @Override
    public List<NightFare> getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        return this.getNullableResult(callableStatement.getString(columnIndex));
    }

    public List<NightFare> getNullableResult(String value) {
        if (value == null) return new ArrayList<>();
        try {
            return MAPPER.readValue(value, new TypeReference<List<NightFare>>() {});
        } catch (JsonProcessingException e) {
            throw new TypeConversionException(e.getMessage());
        }
    }

}
